package com.xmu.edu.tisp.webservice;
//XmlMaker for service 
//By Chenbo 2011-08-06

import java.io.ByteArrayOutputStream;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import android.database.Cursor;

import com.xmu.edu.tisp.database.BaseService;
import com.xmu.edu.tisp.database.Tables;

public class ServiceXmlMaker {
	
	//write datarow to xml nodes
	public static void recordsToXml(Cursor cursor,Element array){
		int numCols=cursor.getColumnCount();
		for(int col=0;col<numCols;++col){
			Element prop=new Element(cursor.getColumnName(col));
			prop.setText(cursor.getString(col));
			array.addContent(prop);
		}
	}
	
	public static Cursor getNotUpload(String tableName){
		return BaseService.getdb().query(tableName, null, "DT_SYNC_FLAG=?", new String[]{"0"}, null, null, null);
	}
	
	public static Cursor getDetail(String tableName,String fkName,String fkValue){
		return BaseService.getdb().query(tableName, null, fkName+"=?", new String[]{fkValue}, null, null, null);
	}
	
	public static Element createMasterElement(String masterTable,String detailTable){
		Element master1=new Element("master");
		master1.setAttribute("type", masterTable);
		
		Cursor cursor1=getNotUpload(masterTable);
		while(cursor1.moveToNext()){
			Element array=new Element("array");
			master1.addContent(array);
			recordsToXml(cursor1,array);
			
			if(detailTable==null || Tables.primaryKey(detailTable)==null) continue;
			//detail table
			Element detail=new Element("detail");
			detail.setAttribute("type",detailTable );
			array.addContent(detail);
			
			String pkValue=cursor1.getString(cursor1.getColumnIndex(Tables.primaryKey(masterTable)));
			Cursor cursor2=getDetail(detailTable,Tables.primaryKey(masterTable),pkValue);
			while(cursor2.moveToNext()){
				Element arr2=new Element("array");
				detail.addContent(arr2);
				recordsToXml(cursor2,arr2);
			}
			cursor2.close();
		}
		cursor1.close();
		return master1;
	}
	
	//get string of XmlDocument
	public static String xmlAsString(Document doc){
		ByteArrayOutputStream byteRep = new ByteArrayOutputStream();
		Format format = Format.getPrettyFormat();
		format.setEncoding("GB2312");
		XMLOutputter docWriter = new XMLOutputter();
		docWriter.setFormat(format);
		try {
			docWriter.output(doc, byteRep);
			return byteRep.toString();
		} catch (Exception e) {
			return null;
		}
	}
}
